import {
	offiacc,
	memberUserInfo,
	adminUserInfo,
	marketList,
	userMarketList
} from '../../service/index.js'
import store from '../index.js';
import {
	removeParam,
	parseQuery
} from '@/utils/index.js'

import {
	TUILogin
} from '@tencentcloud/tui-core';
// #ifdef APP-PLUS || H5
import {
	TUIChatKit
} from '@/TUIKit';
TUIChatKit.init();
// #endif

let vueVersion = 2;
// #ifdef VUE3
vueVersion = 3;
// #endif

uni.$imStatus = ''

export default {
	namespaced: true,
	state() {
		return {
			system: 'h5',
			token: '',
			userInfo: {},
			list: [],
			setting: {},
			redirect_uri: ''
		}
	},
	mutations: {
		changeToken(state, token) {
			state.token = token
		},
		changeUserInfo(state, userInfo) {
			state.userInfo = userInfo
		},
		changeList(state, list) {
			state.list = list
		},
		changeSystem(state, system) {
			state.system = system
		},
		changeSetting(state, setting) {
			state.setting = setting
		},
		changeRedirectUri(state, redirect_uri) {
			state.redirect_uri = redirect_uri
		}
	},
	actions: {
		// userinfo
		async userinfoAction({
			commit,
			dispatch
		}, payload) {
			return new Promise(async (resolve, reject) => {
				try {
					const {
						appid
					} = parseQuery()
					let api = this.state.login.userInfo.is_sale ? adminUserInfo : memberUserInfo
					const result = await api({
						appid
					})
					if (result.code === 200) {
						// 这里设置token后存在问题
						// commit('changeToken', result.data.api_token)
						commit('changeUserInfo', {
							...result.data,
							...{
								appid: appid
							}
						})
						// 获取配置
						dispatch('marketListAction')
						
						if (!uni.$imStatus) {
							uni.$imStatus = TUILogin.login({
								SDKAppID: result.data.im_sdk_appid,
								userID: result.data.im_user_id,
								userSig: result.data.im_usersig,
								useUploadPlugin: true, // If you need to send rich media messages, please set to true.
								framework: `vue${vueVersion}` // framework used vue2 / vue3
							}).catch(() => {});
						}
						
						resolve()
					}
				} catch (e) {
					reject()
				}
			})
		},
		// 配置
		async marketListAction({
			commit,
			dispatch
		}, payload) {
			try {
				let api = this.state.login.userInfo.is_sale ? marketList : userMarketList
				const result = await api({})
				if (result.code === 200) {
					console.log(result.data)
					let market = {}
					result.data.forEach(v => {
						// if (v.is_enable && !v.is_delete) market[v.id] = v
						market[v.id] = v
					})
					commit('changeSetting', {
						market
					})
				}
			} catch (e) {}
		},
		// 登录
		async loginAction({
			commit,
			dispatch
		}, payload) {
			try {
				const {
					code,
					appid,
					content_id,
					t,
					redirect_uri
				} = parseQuery()
				if (!t) {
					// 境内
					if (this.state.login.userInfo.appid && this.state.login.userInfo.appid != appid) {
						commit('changeToken', '')
						commit('changeUserInfo', {})
						commit('changeList', [])
						commit('changeSetting', {})
						commit('changeRedirectUri', '')
						try {
							uni.removeStorageSync('form');
						} catch (e) {
							// error
						}
					}
					if (!this.state.login.token && this.state.login.system === 'h5') {
						if (code) {
							const res = await offiacc({
								code: code,
								appid: appid,
								content_id: content_id || ''
							})
							if (res.code === 200) {
								commit('changeToken', res.data.api_token)
								commit('changeUserInfo', {
									...res.data,
									...{
										appid: appid
									}
								})
								commit('redirect_uri', redirect_uri || '')
								if (res.data.is_disable === 1) {
									const divElement = document.createElement('div');
									divElement.innerHTML =
										`<div style='position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgb(255, 255, 255); color: #383838; z-index: 99999; text-align: center; padding-top: 20%;'>无权访问</div>`;
									document.body.appendChild(divElement);
								} else {
									// 是否跳转境外 用户走境外 销售走境内
									if (!res.data.is_sale && res.data.cover) {
										// 用户
										// 存储临时参数
										let temporary = Object.assign({}, res.data)
										// 跳转境外
										if (window.location.origin != res.data.domain) {
											// 跳转境外需要把境内state重置
											commit('changeToken', '')
											commit('changeUserInfo', {})
											commit('changeList', [])
											commit('changeSetting', {})
											commit('changeRedirectUri', '')
											try {
												uni.removeStorageSync('form');
											} catch (e) {
												// error
											}
											// 本地调试和发布测试生产做区分
											// 如果非首页，开发环境回调后自行地址栏拼接路由
											let _symbol = ''
											if (process.env.NODE_ENV === 'development') {
												_symbol = `?appid=${appid}&`
											} else {
												_symbol = window.location.hash.indexOf('#') != '-1' ? '&' : '?'
											}
											window.location.href = `${res.data.domain}/user/${window.location.hash}${_symbol}t=${res.data.api_token}&redirect_uri=${encodeURIComponent(window.location.origin)}`
										}
									} else {
										// 销售
										// 获取配置
										dispatch('marketListAction')
										window.location.reload()
									}
								}
							} else {
								// 失败 进入预设页面
					
							}
						} else {
							let http = `${window.location.href}`
							http = removeParam("state", http)
							http = removeParam("code", http)
							// 如果是支付宝支付页面，不进行微信授权
							if (window.location.href.indexOf("ali_pay") !== -1) {} else {
								window.location.href =
									`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(http.replace("#", "virtually"))}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
							}
						}
					}
				} else {
					// 境外
					if (t) {
						commit('changeToken', t)
						commit('changeUserInfo', {
							is_sale: 0
						})
						commit('changeRedirectUri', decodeURIComponent(redirect_uri))
					}
				}
			} catch (e) {}
		},
		// 退出登录
		loginOut({
			state,
			commit
		}) {
			commit('changeToken', '')
			commit('changeUserInfo', {})
			commit('changeList', [])
			commit('changeSetting', {})
			commit('changeRedirectUri', '')
			try {
				uni.removeStorageSync('form');
			} catch (e) {
				// error
			}
		},
	},
	getters: {
		roleId: state => state.userInfo.roleId,
		userId: state => state.userInfo.id,
		nickName: state => state.userInfo.nickName,
		roleName: state => state.userInfo.roleName,
		avatar: state => state.userInfo.avatar,
		phone: state => state.userInfo.phone,
	}
}